package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.ui.animation.AnimationConfig;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditGroup;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteTimerButton;
import com.umeng.analytics.MobclickAgent;

public class SignUp2Fragment extends BaseFragment implements View.OnClickListener, CuteTimerButton.TimerListener {

    private static final String AUTO = "auto";

    public interface SignUpCheckCodeListener {

        /**
         * 注册检查验证码成功
         */
        void signUpCheckCodeSuccess(String phone, String code);
    }

    private SignUpCheckCodeListener mSignUpCheckCodeListener;

    private String phone;

    private String second;

    private boolean first;

    private RelativeLayout mLayout;

    private CuteEditGroup mCegCode;

    private CuteTimerButton mCtbTimer;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mSignUpCheckCodeListener = (SignUpCheckCodeListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement SignUpCheckCodeListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        boolean auto = getArguments().getBoolean(AUTO, true);
        phone = getArguments().getString(SignUpActivity.PHONE);
        second = getString(R.string.button_timer);
        first = true;

        View view = inflater.inflate(R.layout.fragment_signup_2, container, false);
        mLayout = (RelativeLayout) view.findViewById(R.id.layout);
        mCegCode = (CuteEditGroup) view.findViewById(R.id.edit_text_code);
        mCtbTimer = (CuteTimerButton) view.findViewById(R.id.button_timer);
        mCtbTimer.setText(mCtbTimer.getTimeCount() + second);
        mCtbTimer.setTimerListener(this);
        CuteTextView ctvNumber = (CuteTextView) view.findViewById(R.id.text_number);
        String text = getString(R.string.text_code);
        ctvNumber.setText(text + phone);
        CuteButton cbNext = (CuteButton) view.findViewById(R.id.btn_next);
        cbNext.setOnClickListener(this);

        if (auto) {
            startTime();
        }

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getArguments().putBoolean(AUTO, false);
    }

    @Override
    protected void onPageStart() {
        MobclickAgent.onPageStart(Config.UMENG_PAGE_SIGN_2);
    }

    @Override
    protected void onPageEnd() {
        MobclickAgent.onPageEnd(Config.UMENG_PAGE_SIGN_2);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                String code = mCegCode.getContent();
                if (checkCode(code)) {
                    requestSignUpCheckCode(code);
                }
                break;
        }
    }

    @Override
    public void timerStart(View v, int startCount) {
        if (v.getId() == R.id.button_timer) {
            mCtbTimer.setTextColor(Color.LTGRAY);
            mCtbTimer.setText(startCount + second);
            if (first) {
                first = false;
            } else {
                requestSignUpGetCode(phone);
            }
        }
    }

    @Override
    public void timerCount(View v, int currentCount) {
        if (v.getId() == R.id.button_timer) {
            mCtbTimer.setText(currentCount + second);
        }
    }

    @Override
    public void timerEnd(View v) {
        if (v.getId() == R.id.button_timer) {
            mCtbTimer.setText("再次获取");
        }
    }

    public void setSignUpCheckCodeListener(SignUpCheckCodeListener signUpCheckCodeListener) {
        mSignUpCheckCodeListener = signUpCheckCodeListener;
    }

    private void startTime() {
        mCtbTimer.onClick(mCtbTimer);
    }

    public void stopTime() {
        mCtbTimer.stop();
    }

    private boolean checkCode(String content) {
        if (TextUtils.isEmpty(content)) {
            AnimationConfig.shake(getActivity(), mLayout);
            tipShow(R.string.tip_error_code_empty);
            return false;
        }
        return true;
    }

    private void requestSignUpCheckCode(final String code) {
        Client.requestSignUpCheckCode(getActivity(), phone, code, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                dismissProgressDialog();
                Integer success = get(value.toString(), Integer.class);
                if (success == null) {
                    return;
                }
                if (success == 1) { // 验证成功
                    if (mSignUpCheckCodeListener != null) {
                        mSignUpCheckCodeListener.signUpCheckCodeSuccess(phone, code);
                    }
                } else if (success == 0) { // 验证失败
                    tipShow(R.string.tip_error_check);
                }
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }
        }, networkUnavailableSampleImpl());
    }

    private void requestSignUpGetCode(final String phone) {
        // 当未连接网络,或网络连接超时的情况发生时,重置计时器.
        Client.requestSignUpGetCode(getActivity(), phone, new ResponseHandler() {

            @Override
            public void onInnovationExceptionFinish() {
                super.onInnovationExceptionFinish();
                stopTime();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                tipShow(R.string.tip_network_unavailable);
                stopTime();
            }
        });
    }
}
